//
// Created by liushuai on 2020/3/9.
//
#include "digitToInteger.h"
#include <limits>
#include <iostream>
#include <regex>
int digitToInteger(std::string& s){
    int result = 0;
    int maxInt = INT32_MAX;
    int minInt = INT32_MIN;
    char pos=' ';
    for(auto elem:s){
        if(elem=='-'){
            pos = elem;
            continue;
        }else{
            if(pos=='-'){
                if(result<minInt/10||(result==minInt/10&&result%10>minInt%10))
                    result = minInt;
                else
                    result = result*10+(elem-'0');

            }else{
                if(result>maxInt/10||(result==maxInt/10&&result%10>maxInt%10)){
                    result = maxInt;
                    break;
                }else{
                    result = result*10+(elem-'0');
                }
            }

        }
    }
    return result;
}
std::string illegal(std::string str){
    std::string result = "";
    if(str.size()<=0)
        return result;
    else{
        for(auto c:str){
            if(c=='-'||c==' '||(c>='0'&&c<='9')){
                if(c!=' '){
                    result+=c;
                }
            }else{
                break;
            }
        }
    }
    return result;
}
int myAtoi(std::string str) {
    int result = 0;
    if(str!=""){
        std::string current = illegal(str);
//        std::cout<<"current:"<<current<<"\n";
        result = digitToInteger(current);
    }

//    if(regex_search(str,base_match,digit,std::regex_constants::match_continuous)){
//        std::string match_result = base_match[0].str();
////        std::cout<<match_result<<"\n";
//        result = digitToInteger(match_result);
//    }
    return result;
}

